package com.wl156.activities.find;

import java.io.IOException;

import org.ksoap2.serialization.SoapObject;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;

import com.wl156.MyApp;
import com.wl156.R;
import com.wl156.R.id;
import com.wl156.activities.HomeActivity;
import com.wl156.adapters.TruckAdapter;
import com.wl156.model.Certificate;
import com.wl156.model.WebServiceClient;
import com.wl156.widget.ProviceSelector;

public class FindCar extends Activity implements OnClickListener {

	private static final String TAG = null;

	private ProviceSelector mFromProviceSelector;
	private EditText mDriverName;
	private EditText mDriverPhone;
	private EditText mOwnName;
	private EditText mOwnPhone;
	private Spinner mCarModel;
	private EditText mTruckTonnage;
	private RadioGroup mTruckTonnageSymBol;
	private EditText mTruckLength;
	private RadioGroup mTruckLengthSymbol;
	private Button mConfirm;

	private WebServiceClient mWebServiceClient;
	private Certificate mCertificate;
	boolean mProgramStartFindResult = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_find_car);

		mWebServiceClient = new WebServiceClient(this);
		mCertificate = ((MyApp) getApplication()).getCertificateFromXml();

		mFromProviceSelector = (ProviceSelector) findViewById(R.id.provice_selector);
		mFromProviceSelector.setTitle("所在地: ");
		mFromProviceSelector.setProviceRequried(true);
		mCarModel = (Spinner) findViewById(R.id.car_model);
		mDriverName = (EditText) findViewById(R.id.driver_name);
		mDriverPhone = (EditText) findViewById(R.id.driver_phone);
		mOwnName = (EditText) findViewById(R.id.own_name);
		mOwnPhone = (EditText) findViewById(R.id.own_phone);
		mTruckTonnage = (EditText) findViewById(R.id.weight);
		mTruckTonnageSymBol = (RadioGroup) findViewById(R.id.truckTonnageSymbol);
		mTruckLength = (EditText) findViewById(R.id.length);
		mTruckLengthSymbol = (RadioGroup) findViewById(R.id.truckLengthSymbol);
		mConfirm = (Button) findViewById(R.id.confirm);
		mConfirm.setOnClickListener(this);

		new StartTask().execute();
	}

	class StartTask extends AsyncTask<Void, Void, Object> {
		ProgressDialog mDialog;

		@Override
		protected void onPreExecute() {
			mDialog = ProgressDialog.show(FindCar.this, "", "加载中");
		};

		@Override
		protected void onPostExecute(Object result) {
			try {
				if (result instanceof Object[]) {
					Object[] values = (Object[]) result;
					SoapObject truckList = (SoapObject) values[0];
					String[] trucks = new String[truckList.getPropertyCount()];
					for (int i = 0; i < truckList.getPropertyCount(); i++) {
						SoapObject truck = (SoapObject) truckList
								.getProperty(i);
						trucks[i] = truck.getPropertyAsString(1);
					}
					ArrayAdapter<String> adapter = new ArrayAdapter<String>(
							FindCar.this, R.layout.item_simple_dropdown_1line,
							trucks);
					mCarModel.setAdapter(adapter);

					SoapObject myCurrentPlace = (SoapObject) values[1];
					String lv1 = myCurrentPlace.getProperty(0).toString();
					String lv2 = myCurrentPlace.getProperty(1).toString();
					String lv3 = myCurrentPlace.getProperty(2).toString();
					mFromProviceSelector.setProvice(lv1);
					mFromProviceSelector.setCity(lv2);
					// mFromProviceSelector.setRegion(lv3);

					if (!getIntent().getBooleanExtra("isReturn", false)) {
						mProgramStartFindResult = true;
						mConfirm.performClick();
					} else {
						mProgramStartFindResult = false;
					}
				} else {
					// Toast.makeText(FindCar.this, "网络异常，请稍候再试",
					// Toast.LENGTH_LONG)
					// .show();
					AlertDialog.Builder builder = new Builder(FindCar.this);
					builder.setMessage("网络请求超时！");
					builder.setPositiveButton("重试",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									new StartTask().execute();
								}
							});
					builder.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									finish();
								}
							});
					builder.show();
				}
			} catch (Exception e) {
			}

			mDialog.dismiss();
		};

		@Override
		protected Object doInBackground(Void... params) {
			try {
				Object[] values = new Object[2];
				values[0] = mWebServiceClient.commomGetTruckList(mCertificate);
				values[1] = mWebServiceClient
						.commonGetMyCurrentPlace(mCertificate);
				return values;
			} catch (IOException e) {
				return e;
			} catch (XmlPullParserException e) {
				return e;
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.confirm:
			final String startLocationLv1 = mFromProviceSelector.getProvice();
			final String startLocationLv2 = mFromProviceSelector.getCity();
			final String startLocationLv3 = mFromProviceSelector.getRegion();
			final String driverName = mDriverName.getText().toString();
			final String driverMobile = mDriverPhone.getText().toString();
			final String ownerName = mOwnName.getText().toString();
			final String ownerMobile = mOwnPhone.getText().toString();
			Object selectedItem = mCarModel.getSelectedItem();
			final String truckType = selectedItem == null ? "" : selectedItem
					.toString();
			final String truckTonnage = mTruckTonnage.getText().toString();
			final String truckTonnageSymBol = mTruckTonnageSymBol
					.getCheckedRadioButtonId() == R.id.big ? ">=" : "<=";
			final String truckLength = mTruckLength.getText().toString();
			final String truckLengthSymbol = mTruckLengthSymbol
					.getCheckedRadioButtonId() == R.id.big ? ">=" : "<=";

			Intent i = new Intent(this, FindCarResult.class);
			i.putExtra("startLocationLv1", startLocationLv1);
			i.putExtra("startLocationLv2", startLocationLv2);
			i.putExtra("startLocationLv3", startLocationLv3);
			i.putExtra("driverName", driverName);
			i.putExtra("driverMobile", driverMobile);
			i.putExtra("ownerName", ownerName);
			i.putExtra("ownerMobile", ownerMobile);
			i.putExtra("truckType", truckType);
			i.putExtra("truckTonnage", truckTonnage);
			i.putExtra("truckTonnageSymBol", truckTonnageSymBol);
			i.putExtra("truckLength", truckLength);
			i.putExtra("truckLengthSymbol", truckLengthSymbol);
			i.putExtra("mProgramStartFindResult", mProgramStartFindResult);
			i.putExtras(getIntent());
			startActivity(i);
			finish();
			break;
		}
	}
}
